package com.jintian.smart.kernel.web.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Conditional;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

/**
 * 跨域配置
 */
@Configuration
@Conditional(EnvironmentConfig.class)
public class CorsFilterConfig {
    @Autowired
    private SmartWebProperty smartWebProperty;

    /**
     * 跨域配置
     */
    @Bean
    public CorsFilter corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration config = new CorsConfiguration();
        config.setAllowCredentials(true);
        // 设置访问源地址
        config.addAllowedOriginPattern(smartWebProperty.getAccessControlAllowOrigin());
        // 设置访问源请求头
        config.addAllowedHeader(smartWebProperty.getAllowedHeader());
        // 设置访问源请求方法
        config.addAllowedMethod(smartWebProperty.getAllowedMethod());
        // 对接口配置跨域设置
        source.registerCorsConfiguration("/**", config);
        return new CorsFilter(source);
    }
}